﻿using AnesSystem.Controls;
using AnesSystem.Model;
using AnesSystem.Models;
using AnesSystem.Udp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;

namespace AnesSystem
{


    public class UdpMangager : BaseManager<UdpMangager>
    {
        #region Variables

        /// <summary>
        /// 消息列表
        /// </summary>
        private Dictionary<string, UdpMsgAnalysis> _msgList;

        private string _currentSessionId = "";

        #endregion

        #region Constructor

        public UdpMangager()
        {
            _msgList = new Dictionary<string, UdpMsgAnalysis>();
            IpList = new List<string>();
            IsNeedSendMessage = true;
            foreach (var item in DataManager.Instance.ConfigOperationRoomModelList)
            {
                if (string.IsNullOrEmpty(item.Ips)) continue;
                string[] roomIps = item.Ips.Split('|');
                foreach (var ip in roomIps)
                {
                    if (!string.IsNullOrEmpty(ip) && !IpList.Contains(ip))
                    {
                        IpList.Add(ip);
                    }
                }
            }
            Udp.UDPHelper.Instance.ReceivedMsg += Instance_ReceivedMsg;
        }

        #endregion

        #region Properties

        public List<string> IpList { get; set; }

        /// <summary>
        /// 是否需要udp消息
        /// </summary>
        public bool IsNeedSendMessage { get; set; }

        #endregion

        #region 依赖属性

        #endregion

        #region Event

        public event EventHandler<UdpMsgAnalysisArgs> ReceivedMsg;

        #endregion

        #region Private Methods

        #endregion

        #region Public/Protected Methods

        /// <summary>
        /// 发送修改信息
        /// </summary>
        /// <returns></returns>
        public void SendModifyMsg(UdpMsgAnalysis msg)
        {
            if (IsNeedSendMessage)
            {
                msg.SendIp = DataManager.Instance.CurRoom.Ips;
                string json = msg.ObjectToJson();
                Udp.UDPHelper.Instance.SendMsg(json);
            }
        }

        //向服务器端发送UDP消息
        public void SendUdpServerMsg(string methodId, UdpModel udpModel)
        {
            UdpMsgAnalysis udpMsgAnalysis = new UdpMsgAnalysis();

            udpMsgAnalysis.MethodId = methodId;
            udpMsgAnalysis.SystemType = "Anes";
            udpMsgAnalysis.CustomContent = udpModel.ObjectToJson();

            string json = udpMsgAnalysis.ObjectToJson();
            Udp.UDPHelper.Instance.SendMsg2Server(json);
        }

        public void SendUpdMsg(BaseCustomCtrl ctrl)
        {
            UdpMsgAnalysis model = DataManager.Instance.XmlAnalysisModel;
            model.MethodId = Udp.ServiceSign.SYSTEMMODIFY;
            model.SystemType = "Anes";
            AnesSystemModifyInfoModel item = new AnesSystemModifyInfoModel()
            {
                AccountID = DataManager.Instance.CurRoom.Code,
                PatientLink = DataManager.Instance.CurrentPatientLink.Id.ToString(),
                TableName = ctrl.ClassName,
                Ip = DataManager.Instance.CurRoom.Ips
            };
            model.CustomContent = item.ObjectToJson();
            SendModifyMsg(model);
        }

        public void SendUpdMsg<T>(string className, string methodId, T obj)
        {
            UdpMsgAnalysis model = DataManager.Instance.XmlAnalysisModel;
            model.MethodId = methodId;
            model.SystemType = "Anes";
            model.SessionID = Guid.NewGuid().ToString();
            string p = "";
            string pid = "";
            if (obj is PatientLinkModel)
            {
                pid = (obj as PatientLinkModel).Id.ToString();
                //p = obj.ObjectToJsonM();
            }
            else if (!(obj is PatientLinkModel) && DataManager.Instance.CurrentPatientLink != null)
            {
                pid = DataManager.Instance.CurrentPatientLink.Id.ToString();
            }
            AnesSystemModifyInfoModel item = new AnesSystemModifyInfoModel()
            {
                AccountID = DataManager.Instance.Login.Id.ToString(),
                RoomID = DataManager.Instance.CurRoom.Name,
                PatientLinkId = pid,
                PatientLink = p,
                TableName = className,
                Ip = DataManager.Instance.CurRoom.Ips
            };
            model.CustomContent = item.ObjectToJson();
            SendModifyMsg(model);
        }

        #endregion

        #region EventHandlers

        private void Instance_ReceivedMsg(object sender, UdpArgs e)
        {
            UdpMsgAnalysis model = e.Msg.JsonToObject<UdpMsgAnalysis>();
            if (string.IsNullOrEmpty(model.SessionID) || model.SessionID.Equals(_currentSessionId)) return;
            else
                _currentSessionId = model.SessionID;
            if (!string.IsNullOrEmpty(model.SendIp))
            {
                string[] ips = model.SendIp.Split('|');
                foreach (var item in ips)
                {
                    if (!string.IsNullOrEmpty(item) && !IpList.Contains(item))
                    {
                        IpList.Add(item);
                    }
                }
            }
            ReceivedMsg?.Invoke(this, new UdpMsgAnalysisArgs(model));
        }

        #endregion
    }
}
